#include "host_cmd_base.h"
#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#else

#endif // _WIN32

CHostCmd_base::CHostCmd_base()
{
	m_sbuf = NULL;
	m_fd = 0;
	m_clientID = 0;
	m_pClient_addr = NULL;
	m_client_len = 0;
	m_show_receive = true;
	m_show_send = true ;
}

CHostCmd_base::~CHostCmd_base()
{
	if(NULL != m_sbuf)
	{
		delete [] m_sbuf;
	}

}

int CHostCmd_base::AttachSocket(SOCKET fd_svr, struct sockaddr* client_addr, int client_len)
{
	m_fd = fd_svr;
	m_pClient_addr = client_addr;
	m_client_len = client_len;
	m_bUdp = true;
	return 0;
}

int CHostCmd_base::Destroy()
{
	int ret = 0;
	if(NULL != m_sbuf)
	{
		delete [] m_sbuf;
	}

	return ret;
}
/*
virtual int AnalysisCmd(char* cmd_buf, int cmd_len) = 0;
int CHostCmd_base::AnalysisCmd(char * cmd_buf,int cmd_len)
{
	int ret = 0;

	m_byte_parser.init_data(cmd_buf, cmd_len);
	try {
		luacpp::call<void>(m_l, "analysis_cmd", m_byte_parser);
	}
	catch (std::string& err)
	{
		printf("%s\n", err.c_str());
	}
	return ret;
}
*/
uint32_t CHostCmd_base::GetCRC32_FromBuf(unsigned char * cmd_buf,uint32_t data_sz)
{
	//DVR_APP_HEAD * pApp = (DVR_APP_HEAD * )cmd_buf;
	//uint32_t crc_cmd = 0;

	//unsigned char * crc_data = cmd_buf + 8 + pApp->dataLen;
	//if(pApp->dataLen > data_sz)
	//{
	//	printf("head info datalen error.data size %d \n",data_sz);
	//	return 0;
	//}

	//crc_cmd =   (uint32_t)crc_data[0]| (uint32_t)crc_data[1]<<8|
	//			(uint32_t)crc_data[2]<<16|
	//			(uint32_t)crc_data[3]<<24;

//	return crc_cmd;
	return 0;
}

int CHostCmd_base::CheckCRC32(char * cmd_buf,uint32_t len)
{
	uint32_t cnt_crc    = 0;
	uint32_t trans_crc  = 0;
	//DVR_APP_HEAD * pApp = (DVR_APP_HEAD * )cmd_buf;

	//if(pApp->dataLen +4  > len)
	//{
	//	return ERR_DATA_AREA;
	//}

	//���¼����CRC
	//cnt_crc = lhn_crc32(cmd_buf +2, pApp->dataLen+ 6);

	//��ȡ�����������CRC
	//trans_crc = GetCRC32_FromBuf(cmd_buf,len);

	//У��֤CRC32��ͨ�����򷵻ش��󣬲���Ҫ������������
	if(0)
	{
		if(cnt_crc != trans_crc)
		{
		//	TRACE("ERROR CRC32 re count %d transfer crc %d .\n",cnt_crc,trans_crc);
			return -1;
		}
	}

	return 0;
}

int CHostCmd_base::RespondDataPkt(char * buf, int data_sz)
{
	int ret  = 0;
	if (m_bUdp)
	{
		ret = sendto(m_fd, buf, data_sz, 0, m_pClient_addr, m_client_len);
	}
	else
	{
		ret = send(m_fd, buf, data_sz, 0);
	}

	if(ret < 0)
	{
        int err = 0;
#ifdef _WIN32
        err = GetLastError();
#else
        err = errno;
#endif
	//	TRACE("Send error m_fd %d  data_sz %d ret %d errno %d .\n",m_fd,data_sz,ret,err);
	}

	return ret;
}



int CHostCmd_base::AttachSocketTCP(SOCKET fd, int clientID)
{
	int ret = 0;
	m_fd = fd;
	m_heat_last = 0;
	if (m_sbuf == NULL)
	{
		m_sbuf_sz = 64 << 10;
		m_sbuf = new char[m_sbuf_sz];
	}
	m_clientID = clientID;
	return ret;
}


